<?php


namespace app\api\helpers\v1\traits;


use app\api\model\v1\SystemConfig;
use PhpOffice\PhpSpreadsheet\IOFactory;

trait FileUpload
{
    /**
     * @param $file //文件
     * @param $folder //文件夹名称
     * 上传图片
     * @return array
     */
    public function save($file, $folder)
    {
        $saveName = \think\facade\Filesystem::disk('public')
            ->putFile($folder, $file);
        $path = str_replace('\\', '/', $saveName);
        return [
            'path' => $path,
        ];
    }

    /**
     * @param $file
     * @param $folder
     * @param $fileName
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 8:29
     * @return array
     * 指定文件名称
     */
    public function saveFileAs($file, $folder, $fileName)
    {
        $saveName = \think\facade\Filesystem::disk('public')
            ->putFileAs($folder, $file, $fileName);
        $path = str_replace('\\', '/', $saveName);
        return [
            'path' => $path,
        ];
    }

    //创建文件夹
    public function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }
        if (!mkdir(dirname($dir), $mode)) {
            return false;
        }
        return @mkdir($dir, $mode);
    }


    /**
     * @param $file
     * @param $folder
     * @param string $type multistage  多级    stage 单级 直接导入
     * @User: 刘海龙
     * @Date: 2021/8/25
     * @Time: 18:18
     * @return array
     */
    public function saveImportExcel($file, $folder, $type = 'multistage')
    {
        $saveName = \think\facade\Filesystem::disk('public')->putFile($folder, $file);
        $path = app()->getRootPath() . 'public/storage/' . str_replace('\\', '/', $saveName);
        $returnData = $this->loadExcel($path);
        if ($type === 'multistage'){
            $data = $this->dadaFilter($returnData); //导入模版
        }else{
            $data = $this->dadaFilter2($returnData); //导入模版样本
        }
        return $data;
    }


    //载入excel
    public function loadExcel($filePath)
    {
        $inputFileType = IOFactory::identify($filePath);
        $reader = IOFactory::createReader($inputFileType);
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load($filePath); //载入excel表格
        $res_arr = array();
        $reader = $spreadsheet->getWorksheetIterator();
        foreach ($reader as $sheet) {
            //读取表内容
            $content = $sheet->getRowIterator();
            //逐行处理
            foreach ($content as $key => $items) {
                $rows = $items->getRowIndex();              //行
                $columns = $items->getCellIterator();       //列
                $row_arr = array();
                //确定从哪一行开始读取
                if ($rows < 2) {
                    continue;
                }
                //逐列读取
                foreach ($columns as $head => $cell) {

                    $data = $cell->getValue();

                    $row_arr[] = $data;
                }

                array_push($res_arr, array_values(array_filter($row_arr, function ($var) {
                    return $var !== null;
                })));

            }
        }
        return $res_arr;
    }


    //处理excel (多级) 导入模版
    public function dadaFilter(array $array)
    {
        $filterData = [];
        $k1 = $i1 = $j1 = $k2 = $i2 = $i3 = $i4 = 0;
//        foreach ($array as $data) {
//            if (count($data) == 7) {
//                $i1 = $j1 = 0;
//                $filterData[$k1] = ['a' => $data[0]];
//                $filterData[$k1]['item'][$i1] = [
//                    'b' => $data[1],
//                ];
//                $filterData[$k1]['item'][$i1]['item'][] = [
//                    'c' => $data[2],
//                    'd' => $data[3],
//                    'e' => $data[4],
//                    'f' => $data[5],
//                    'g' => $data[6]
//                ];
//                $k2 = $k1;
//                $i2 = $i1;
//                $i4 = $i3 = $j1;
//                $k1++;
//                $i1++;
//                $j1++;
//            }
//
//            if (count($data) == 6) {
//                $filterData[$k2]['item'][$i1] = [
//                    'b' => $data[0],
//                ];
//                $filterData[$k2]['item'][$i1]['item'][] = [
//                    'c' => $data[1],
//                    'd' => $data[2],
//                    'e' => $data[3],
//                    'f' => $data[4],
//                    'g' => $data[5],
//                ];
//                $i2 = $i1;
//                $i4++;
//                $i1++;
//            }
//            if (count($data) == 5) {
//                $filterData[$k2]['item'][$i1] = [
//                    'c' => $data[0],
//                ];
//                $filterData[$k2]['item'][$i1]['item'][] = [
//                    'd' => $data[1],
//                    'e' => $data[2],
//                    'f' => $data[3],
//                    'g' => $data[4],
//                ];
//                $i2 = $i1;
//                $i4++;
//                $i1++;
//            }
//            if (count($data) == 4) {
//                $filterData[$k2]['item'][$i2]['item'][] = [
//                    'd' => $data[0],
//                    'e' => $data[1],
//                    'f' => $data[2],
//                    'g' => $data[3]
//                ];
//                $i3++;
//                $j1++;
//            }
//////
//        }
        foreach ($array as $data) {
            if (count($data) == 8) {
                $i1 = $j1 = 0;
                $filterData[$k1] = ['a' => $data[0]];
                $filterData[$k1]['child'][$i1] = [
                    'b' => $data[1],
                    'c' => $data[2],
                    'd' => $data[3],
                ];
                $filterData[$k1]['child'][$i1]['child'][] = [

                    'e' => $data[4],
                    'f' => $data[5],
                    'g' => $data[6],
                    'i' => $data[7],
                ];
                $k2 = $k1;
                $i2 = $i1;
                $i4 = $i3 = $j1;
                $k1++;
                $i1++;
                $j1++;
            }
            if (count($data) == 7) {
                $filterData[$k2]['child'][$i1] = [
                    'b' => $data[0],
                    'c' => $data[1],
                    'd' => $data[2],
                ];
                $filterData[$k2]['child'][$i1]['child'][] = [
                    'e' => $data[3],
                    'f' => $data[4],
                    'g' => $data[5],
                    'i' => $data[6]
                ];
                $i2 = $i1;
                $i4++;
                $i1++;
            }
            if (count($data) == 4) {
                $filterData[$k2]['child'][$i2]['child'][] = [
                    'e' => $data[0],
                    'f' => $data[1],
                    'g' => $data[2],
                    'i' => $data[3]
                ];
                $i3++;
                $j1++;
            }
        }
        return array_values($filterData);
    }

    /**
     * @param array $array
     * @User: 刘海龙
     * @Date: 2021/11/10
     * @Time: 17:29
     * @return array
     * 导入样本点
     */
    public function dadaFilter2(array $array){

        $filterData = [];
        $k1 = $i1 = $j1 = $k2 = $i2 = $i3 = $i4 = 0;
        foreach ($array as $data) {
            if (count($data) == 2) {
                $i1 = $j1 = 0;
                $filterData[$k1] = ['a' => $data[0]];
//                $filterData[$k1]['item'][$i1] = [
//                    'b' => $data[1],
//                ];
                $filterData[$k1]['item'][$i1][] = [
                    'b' => $data[1],
                ];
                $k2 = $k1;
                $i2 = $i1;
                $i4 = $i3 = $j1;
                $k1++;
                $i1++;
                $j1++;
            }
            if (count($data) == 1) {
                $filterData[$k2]['item'][$i2][] = [
                    'b' => $data[0],
                ];
                $i3++;
                $j1++;
            }
        }
        return $filterData;
    }
    /**
     * @param $str
     * @User: 刘海龙
     * @Date: 2021/9/2
     * @Time: 11:59
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 过滤敏感字符
     */
    public function filterSensitive($str)
    {
        $config = SystemConfig::where(['name' => 'sensitive'])->find();
        if (!is_null($config)) {
            //获取敏感字符的字符串并且转换为数组
            $sensitive_string = $config['value'];
            $sensitive_arr = explode(',', $sensitive_string);
            $word = array_combine($sensitive_arr, array_fill(0, count($sensitive_arr), '****'));
            $filter_str = strtr($str, $word);
        } else {
            $filter_str = $str;
        }
        return $filter_str;
    }


    /**
     * @param $file_path
     * @User: 刘海龙
     * @Date: 2021/9/13
     * @Time: 16:48
     * 下载excel 模板
     */
    public function downloadExcel($file_path)
    {
        header("Content-type:text/html;charset=utf-8");
        if (!file_exists($file_path)) {
            echo "没有该文件文件";
            return;
        }
        $fp = fopen($file_path, "r");
        $file_size = filesize($file_path);
        //下载文件需要用到的头
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length:" . $file_size);
        Header("Content-Disposition: attachment; filename=" . $file_path);
        $buffer = 1024;
        $file_count = 0;
        //向浏览器返回数据
        while (!feof($fp) && $file_count < $file_size) {
            $file_con = fread($fp, $buffer);
            $file_count += $buffer;
            echo $file_con;
        }
        fclose($fp);

    }


    /**
     * @param array $array
     * @User: 刘海龙
     * @Date: 2021/10/8
     * @Time: 14:51
     * @return array
     * 处理学习题库
     */
    public function dataLearn(array $array)
    {
        $filterData = [];
        $k1 = $i1 = $j1 = $k2 = $i2 = $i3 = $i4 = 0;
        foreach ($array as $data) {
            if (count($data) == 6) {
                $i1 = $j1 = 0;
                $filterData[$k1] = ['title' => $data[0]];
                $filterData[$k1]['item'][$i1] = [
                    'topic_title' => $data[1],
                    'learn_answer' => $data[2],
                    'question_type' => $data[3],
                    'answer_explain' => $data[4],
                ];
                $filterData[$k1]['item'][$i1]['item'][$j1] = [
                    'option_title' => $data[5],
                ];
                $k2 = $k1;
                $i2 = $i1;
                $i4 = $i3 = $j1;
                $k1++;
                $i1++;
                $j1++;
            }
            if (count($data) == 5) {
                $filterData[$k2]['item'][$i1] = [
                    'topic_title' => $data[0],
                    'learn_answer' => $data[1],
                    'question_type' => $data[2],
                    'answer_explain' => $data[3],
                ];
                $filterData[$k2]['item'][$i1]['item'][] = [
                    'option_title' => $data[4],
                ];
                $i2 = $i1;
                $i4++;
                $i1++;
            }
            if (count($data) == 1) {
                $filterData[$k2]['item'][$i2]['item'][] = [
                    'option_title' => $data[0],
                ];
                $i3++;
                $j1++;
            }
        }
        return $filterData;
    }

}
